package com.chixing.service.impl;

import com.chixing.pojo.Myorder;
import com.chixing.service.MyCouponService;
import com.chixing.service.OrderService;
import com.chixing.util.ServerResponse;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.amqp.rabbit.annotation.*;



import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author YHB
 * @date 2021/11/2  22:20
 */
@Service
public class MsgListener {
    @Autowired
    private MyCouponService myCouponService;
    @Autowired
    private OrderService orderService;
    /**
     * 默认情况下,如果没有配置手动ACK, 那么Spring Data AMQP 会在消息消费完毕后自动帮我们去ACK
     * 存在问题：如果报错了,消息不会丢失,但是会无限循环消费,一直报错,如果开启了错误日志很容易就吧磁盘空间耗完
     * 解决方案：手动ACK,或者try-catch 然后在 catch 里面将错误的消息转移到其它的系列中去
     * spring.rabbitmq.listener.simple.acknowledge-mode = manual
     *  list 监听的内容
     */
    @RabbitListener(queues = "ORDER_QUEUE")
    public void getOrderMessage(Myorder myorder, Channel channel, Message message)throws InterruptedException, IOException {
        System.out.println("消息接收到了");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //模拟执行任务+
        myorder = orderService.getByOrderNum(myorder.getOrderNum());
        try {
            if(myorder.getStatus() == 1){

               orderService.updateMyOrderStatus(myorder.getOrderId(),3);
                System.out.println("订单超时:" + myorder.getOrderNum());

            }else
                System.out.println(myorder.getOrderNum() + ":该订单已支付");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }catch (Exception e){
            System.out.println(("============消费失败,尝试消息补发再次消费!=============="));
            System.out.println(e.getMessage());
            /**
             * basicRecover方法是进行补发操作，
             * 其中的参数如果为true是把消息退回到queue但是有可能被其它的consumer(集群)接收到，
             * 设置为false是只补发给当前的consumer
             */
            channel.basicRecover(false);

        }

    }

}
